package com.qf.homeworkssm.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import com.qf.homeworkssm.entity.User;
import com.qf.homeworkssm.service.UserService;
import com.qf.homeworkssm.utils.Contants;
import com.qf.homeworkssm.vo.InUserVo;
import com.qf.homeworkssm.vo.ResultVo;
import com.qf.homeworkssm.vo.TableVo;
import com.qf.homeworkssm.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;

@RestController
@RequestMapping("/user")
@Slf4j //添加该注解后可以使用log对象进行日志打印
public class UserController {

    @Autowired
    private UserService userService;



    @RequestMapping("/login")
    public ResultVo login(String  autologin ,
                          HttpServletResponse response,
                          String username, String password,
                          String capchar, HttpSession session){

        log.info("{username={},password={},capchar={}}",username,password,capchar);
        //1.处理验证是否正确
        String captcha = (String) session.getAttribute("captcha");
        System.out.println(captcha);
        if (!capchar.equals(captcha)) {
            return  new ResultVo(Contants.FAIL_CODE,"验证码错误");
        }

        //2.调用service层方法进行登录验证
        User user = userService.login(username,password);
        log.info("调用service层方法校验用户名和密码，返回的对象user={}",user);


        //3.如果user不是null则代表登录成功，如果user为null，失败
        if (user!=null){
            return  new ResultVo(Contants.SUCCESS_CODE,"登录成功");
        }else {
            return  new ResultVo(Contants.FAIL_CODE,"登录失败");
        }
    }

    @RequestMapping("/login2")
    public  ResultVo login2(String  autologin ,
                            HttpServletResponse response, String username, String password, String capchar, HttpSession session){
        log.debug("{username={},password={}}",username,password);
        //1.处理验证是否正确
        String captcha = (String) session.getAttribute("captcha");
        System.out.println(captcha);
        if (!capchar.equals(captcha)) {
            return  new ResultVo(Contants.FAIL_CODE,"验证码错误");
        }

        //调用service获取user，如果user不为空，返回成功，为空错我
        User user = userService.getUserss(username,password);
        log.info("调用service层方法校验用户名和密码，返回的对象user={}",user);

        //如果用户登录成功，把user对象存入session中
        session.setAttribute(Contants.SESSION_USER_KEY,user);

        log.debug("用户设置免登录：");
        if ("on".equals(autologin)){
            log.debug("用户设置免登录");
            //生成用户免登录的cookie
            String md5password = DigestUtil.md5Hex(password);
            String cookievalue = username+"-"+md5password;
            Cookie cookie = new Cookie(Contants.USER_TOKEN, cookievalue);
            cookie.setPath("/"); //设置cookie为该域的顶级cookie
            cookie.setMaxAge(60*60*24*14); //两周有效期
            log.debug("用户设置免登录：cookie={}",cookie);
            response.addCookie(cookie);

        }

        if (user!=null){

            return new ResultVo(Contants.SUCCESS_CODE,"登录成功");
        }else {
            return new ResultVo(Contants.FAIL_CODE,"登陆失败");
        }





    }

    /*用户注册接口，用于文件注册上传*/
    @PostMapping("/regist")
    public ResultVo regist(HttpSession session , UserVo userVo) throws IOException, ParseException {
        log.info("用户注册请求处理：userVo={}",userVo);
        //1.处理验证是否正确
        String captcha = (String) session.getAttribute("captcha");
        System.out.println(captcha);
        if (!userVo.getCapchar().equals(captcha)) {
            return  new ResultVo(-1,"验证码错误");
        }

        //2.调用service完成注册处理逻辑
        //物理路径
        String realPath = session.getServletContext().getRealPath("/upload");

        ResultVo resultVo =  userService.regist(userVo,realPath,session);

        return resultVo;
    }


    @RequestMapping("/headPortrait")
    public void headPortrait(HttpSession session, HttpServletResponse response) throws IOException {

        //调用service查询user的图片名称
        User user = (User) session.getAttribute("user");

        String name = user.getPhotopath();
        System.out.println("图片名称name:"+name);
        //获得要下载文件的绝对路径
        String path = session.getServletContext().getRealPath("/file");
        //文件的完整路径
        String real_path = path+"\\"+name;

        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename="+name);

        //读取目标文件，写出给客户端
        IOUtils.copy(new FileInputStream(real_path), response.getOutputStream());

    }

    @RequestMapping("/getUsername")
    public String getUsername(HttpSession session){
        User user = (User) session.getAttribute("user");

        String name = user.getName();
        return name;


    }
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 50, 4, 5);
        //将验证码放入session
        request.getSession().setAttribute("captcha", captcha.getCode());
        captcha.write(response.getOutputStream());
    }


    @GetMapping("/checkusername")
    public ResultVo checkusername(String username){
        //调用service检查用户名是否存在
        ResultVo resultVo = userService.checkUserNmae(username);
        return  resultVo;
    }


    /*用户数据表格分页查询
     * page 页号
     * limit 页大小*/
    @RequestMapping("/getAllUsers")
    public TableVo<User> getAlluser(Integer page, Integer limit){

        log.debug("查询用户，page={}，limit={}",page,limit);
        TableVo tableVo = userService.getAllUserByPage(page,limit);
        log.debug("查询到的结果为，tablevo={}",tableVo);
        return tableVo;
    }
    @RequestMapping("/getUsers")
    public TableVo<User> getUsers(Integer page, Integer limit){

        log.debug("查询用户，page={}，limit={}",page,limit);
        TableVo tableVo = userService.getAll(page,limit);
        log.debug("查询到的结果为，tablevo={}",tableVo);
        return tableVo;


    }


    @PostMapping("/del")
    public ResultVo del(Integer[] ids){
        Integer user = userService.delUser(ids);
        if (user>0){
            return new ResultVo(Contants.SUCCESS_CODE,"删除成功");
        }else{
            return new ResultVo(Contants.FAIL_CODE,"删除失败");
        }
    }

//    @PostMapping("/del")
//    public ResultVo dels(@RequestParam("ids") List<Integer> ids){
//
//        log.debug("收到参数ids = {}",ids.size());
//       ResultVo resultVo =  userService.delteUsers(ids);
//       return resultVo;
//
//    }


    @PostMapping("/add")
    public ResultVo add(InUserVo users){
        log.debug("接收到参数users = {}",users);
            Integer user = userService.InserInUsers(users);

            if (user>0){
                return new ResultVo(Contants.SUCCESS_CODE,"添加成功");
            }else {
                return new ResultVo(Contants.FAIL_CODE,"添加失败");
            }
    }



    @RequestMapping("/update")
    public ResultVo update(User user){
        log.debug("收到参数user ={}" ,user);
        UserVo userVo = new UserVo();
        ResultVo resultVo = userService.updateUser(user);
        return resultVo;


    }


    /**
     * 带查询结构的数据表格接口
     * @param page
     * @param limit
     * @param userVo
     * @return
     */
    @GetMapping("/getUserByCondition")
    public TableVo<User> getUserByCondition(Integer page,Integer limit,UserVo userVo){

        log.debug("收到参数page = {}，limit={} ，userVo={}",page,limit,userVo);
        TableVo<User> tableVo =userService.getUserByCondition(page,limit,userVo);
        return tableVo;

    }


    @GetMapping("/export")
    public ResultVo export() throws IOException {


        //1.调用service层 进行文件导出
        String fileName = userService.export();


        //2.返回文件名包含resultVo
        return  new ResultVo(Contants.SUCCESS_CODE,"文件导出成功",fileName);
    }


}

